package net.dl.ss.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dl.ss.dao.CategCoupleDao;
import net.dl.ss.dao.CategDanceDao;
import net.dl.ss.domain.CategCouple;
import net.dl.ss.domain.CategDance;
import net.dl.ss.service.ContextManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
@Controller
public class CategCouplesController extends BaseController {
	protected final Log logger = LogFactory.getLog(getClass());
	private final CategCoupleDao categCoupleDao;
	
	@Autowired
	public CategCouplesController(CategCoupleDao categCoupleDao) {
		this.categCoupleDao = categCoupleDao;
	}
	
	@RequestMapping("/addCategCouple.htm")
	public void addCategCoupleHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");

		Long categoryId = ContextManager.getCurrentCategory(request);
	    if(categoryId!=null) {
	    	Long id = getParameter(request,"id",Long.class);
	    	try {
				CategCouple cc = new CategCouple();
				cc.setCoupleId(id);
				cc.setCategoryId(categoryId);
	    		this.categCoupleDao.saveEntity(cc);
				os.print("{success:true}");
			} catch(Exception ex) {
				logger.error(ex.getMessage());
			}
	    } else {
	    	os.print("{success:false}");
	    }
	    os.close();
	}
	
	@RequestMapping("/remCategCouple.htm")
	public void remCategCoupleHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");
		try {
			String id = request.getParameter("id");
			if(id!=null && !"".equals(id)) {
				this.categCoupleDao.deleteByCategAndCouple(ContextManager.getCurrentCategory(request), Long.parseLong(id));
				os.print("{success:true}");
			} else {
				os.print("{success:false}");
			}
		} catch(Exception ex) {
			logger.error(ex.getMessage());
		}
	    os.close();
	}
	
}
